package Java8新特性;

import org.junit.Test;

import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

/*
     构造器引用
        格式: ClassName::new
        与函数式接口相结合,自动与函数式接口中方法兼容
        和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致,抽象方法的返回值类型即为构造器所属的类型

     数组引用
        将数组看作是一个特殊的类,写法与构造器引用相同
 */
public class Lambda04 {

    /*
        Supplier中的T get()
        Employee的空参构造器 Employee()  --> 返回值为创建好的对象
         这两个方法中,都有相同的结构,没有形参,有返回值,且返回值类型也相同
     */
    @Test
    public void test1(){
        //原始写法
        Supplier<Employee> sup1 = new Supplier<Employee>() {
            @Override
            public Employee get() {
                return new Employee();
            }
        };

        //Lambda写法
        Supplier<Employee> sup2 = () -> new Employee();

        //构造器引用
        Supplier<Employee> sup3 = Employee::new;
        sup3.get();
    }

    /*
        Function中的R apply(T t)
     */
    @Test
    public void test2(){
        //Lambda写法
        Function<Integer,Employee> fun1 = id -> new Employee(id);
        Employee employee = fun1.apply(1001);
        System.out.println(employee);

        //构造器引用
        Function<Integer,Employee> fun2 = Employee::new;
        employee = fun2.apply(1001);
        System.out.println(employee);
    }

    /*
        BiFunction中的R apply(T t,U u)
     */
    @Test
    public void test3(){
        //Lambda写法
        BiFunction<Integer,String,Employee> bi1 = (id,name) -> new Employee(id,name);
        Employee employee = bi1.apply(1001, "Tom");
        System.out.println(employee);

        //构造器引用
        BiFunction<Integer,String,Employee> bi2 = Employee::new;
        employee = bi2.apply(1001, "Tom");
        System.out.println(employee);
    }

    /*
        数组引用
        Function中的R apply(T t)
     */
    @Test
    public void test4(){
        Function<Integer,String[]> fun1 = length -> new String[length];
        String[] apply = fun1.apply(5);
        System.out.println(Arrays.toString(apply));

        //数组引用
        Function<Integer,String[]> fun2 = String[]::new;
        apply = fun2.apply(5);
        System.out.println(Arrays.toString(apply));
    }
}
